package cre.tomcat4.ch02.processor;

import cre.tomcat4.ch02.Constant;
import cre.tomcat4.ch02.Request;
import cre.tomcat4.ch02.Response;

import javax.servlet.Servlet;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;

/**
 * @Author penglai
 * @Date 2017/1/3.
 */
public class ServletProcessor1 {
    public void process(Request request, Response response) {
        String uri = request.getUri();
        String servletName = gainServletName(uri);

        URLClassLoader loader = gainLoader();
        Class sClass = null;
        try {
            sClass = loader.loadClass(Constant.SERVLET_CLASS_PACKAGE + servletName);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            System.out.println(loader.getURLs());
        }

        Servlet servlet = null;
        try {
            servlet = (Servlet) sClass.newInstance();
            servlet.service(request, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private URLClassLoader gainLoader() {
        URL[] urls = new URL[1];
        File webapp = new File(Constant.CLASS_PATH);
        URL url = null;
        try {
            url = new URL("file", null, webapp.getAbsolutePath() + File.separator);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }

        urls[0] = url;
        URLClassLoader classLoader = new URLClassLoader(urls);
        return classLoader;
    }

    private String gainServletName(String uri) {
        return uri.substring("/servlet".length() + 1);
    }
}
